﻿jQuery.mvc = {};
jQuery.mvc.animation = 'fadeIn';
jQuery.mvc.animationSpeed = '';

jQuery.mvcJson = function( url, callback ) {
    jQuery.mvc.request(url, showResultIn, "POST", true, null, callback);
};

jQuery.fn.mvcJsonForm = function ( callback) {
    var t = jQuery(this);
    var url = t.attr('action');
    jQuery.mvc.request(url, null, "POST", true, t.serialize(), callback);
}

jQuery.fn.mvcAjaxForm = function ( showResultIn, callback) {
    var t = jQuery(this);
    var url = t.attr('action');
    jQuery.mvc.request(url, showResultIn, "POST", false, t.serialize(), callback);
}
	    
jQuery.mvc.request = function( url, showResultIn, type, json, data, callback ) {
    if (typeof(jQuery.mvc.originalState) == 'undefined')
        jQuery.mvc.originalState = jQuery(document.body).html();
        
    if ( jQuery.isFunction( data ) ) {
	    callback = data;
	    data = "";
    }

    if (!data)
        data = "";
    
    if ( jQuery.isFunction( showResultIn ) ) {
	    callback = showResultIn;
	    showResultIn = null;
    }
    
    if (showResultIn)
    {
        showResultIn = jQuery(showResultIn);
    }
    
    return jQuery.ajax({
	    type: type,
	    url: url,
	    data: data,
	    success: function(resultObj) {
	        jQuery.mvc.processRequest(resultObj, callback,false,showResultIn);
	    },
	    error: function(resultObj, status) {
	        jQuery.mvc.processRequest(resultObj, null, true, showResultIn);
	    },
	    dataType: (json ? "json" : null),
	    beforeSend: (!json ? null : function(xml) {
	        xml.setRequestHeader("X-IsJson", "true");
	    })
    });
};

jQuery.mvc.clearMessages = function() {
    jQuery('#errors').html('');
    jQuery('#messages').html('');
}

jQuery.fn.mvcAddMessage = function(msg) {
    var t = jQuery(this);
    if (t.html() == '')
        t.html('<ul></ul>');
    var ul = jQuery('ul', t);
    ul.append('<li>' + msg + '</li>');
}

jQuery.mvc.processRequest = function (resultObj, callback, isError, showResultIn) {
    jQuery.mvc.clearMessages()
    var msgContainer = jQuery('#messages');
    var errorContainer = jQuery('#errors');
    if ((typeof(resultObj) != 'undefined') &&
        jQuery.isFunction(resultObj.getResponseHeader) &&
        resultObj.getResponseHeader("Content-Type").indexOf("json") >= 0)
    {
        resultObj = eval("(" + resultObj.responseText + ")");
    }
    
    var result = true;
    var errorSet = false;
    if (jQuery.isFunction(callback))
        result = callback(resultObj);
    
    if (result != false && typeof(resultObj) != 'undefined')
    {
        if (msgContainer && typeof(resultObj.Messages) != 'undefined')
        {
            jQuery(resultObj.Messages).each(function(t){
                msgContainer.mvcAddMessage(this);
            });
        }
        if (errorContainer && typeof(resultObj.Errors) != 'undefined')
        {
            jQuery(resultObj.Errors).each(function(t) {
                errorContainer.mvcAddMessage(this);
            });
            errorSet = true;
        }
    }
    if (result && showResultIn)
    {
        var html = typeof(resultObj.responseText) == 'undefined' ? 
            resultObj : resultObj.responseText;
        
        showResultIn = jQuery(showResultIn);
        var resId = showResultIn.attr('ID');
        showResultIn.replaceWith(html);
        showResultIn = jQuery('#' + resId);
        if(jQuery.mvc.animation)
            showResultIn.hide();

        var ajaxMsg = jQuery('#ajaxmessages');
        msgContainer.html(ajaxMsg.html());
        ajaxMsg.remove();
        
        var errorMsg = jQuery('#ajaxerrors');
        errorContainer.html(errorMsg.html());
        errorMsg.remove();
        errorSet = errorMsg.size() > 0;
        jQuery('a.ajaxlink', showResultIn).ajaxify();
        if(jQuery.mvc.animation)
            jQuery(showResultIn).animate({opacity: "show"}, jQuery.mvc.animation, jQuery.mvc.animationSpeed);
    }
    if (isError && !errorSet)
    {
        jQuery(document.body).html(resultObj.responseText);
    }
    
    return result;
}
jQuery.mvc.initialize = function() {
    if (typeof(jQuery.mvc.originalState) != 'undefined')
        jQuery(document.body).html(jQuery.mvc.originalState);
    jQuery('a.ajaxlink').ajaxify();
    $("#loading").ajaxStart(function(){
       $(this).show();
     });
    $("#loading").ajaxStop(function(){
       $(this).hide();
     });
}
jQuery().ready(function() {
    jQuery.mvc.initialize();
})

jQuery.fn.ajaxify = function() {
    return this.each(function() {
        var link = jQuery(this);
        if(link.attr('href').substr(1, 1) != '#')
        {
            link.attr('href', '#' + link.attr('href')); 
            link.history(function() {
                var target = link.attr('meta:ajaxtarget');
                var hash = link.attr('href').substr(0,1)
                var url = link.attr('href');
                while (hash == '#') {
                    url = url.substr(1);
                    hash = url.substr(0,1);
                }
                jQuery.mvc.request(url, target, "GET", false, 'fullpage=true');
            });
        }
    })
};
jQuery.ajaxHistory.initialize(jQuery.mvc.initialize);
